<template>
  <div class="medical-records">
    <!-- 顶部状态栏 -->
    <div class="status-bar">
      <div class="status-left">9:41</div>
      <div class="status-right">
        <div class="signal"></div>
        <div class="wifi"></div>
        <div class="battery"></div>
      </div>
    </div>

    <!-- 头部导航 -->
    <div class="header">
      <div class="nav-back" @click="goBack">
        <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2">
          <path d="M19 12H5M12 19l-7-7 7-7"/>
        </svg>
      </div>
      <h1 class="page-title">医疗记录</h1>
      <div class="nav-actions">
        <div class="nav-action" @click="toggleSearch">
          <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2">
            <circle cx="11" cy="11" r="8"/>
            <path d="m21 21-4.35-4.35"/>
          </svg>
        </div>
        <div class="nav-action" @click="toggleFilter">
          <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2">
            <line x1="8" y1="6" x2="21" y2="6"/>
            <line x1="8" y1="12" x2="21" y2="12"/>
            <line x1="8" y1="18" x2="21" y2="18"/>
            <line x1="3" y1="6" x2="3.01" y2="6"/>
            <line x1="3" y1="12" x2="3.01" y2="12"/>
            <line x1="3" y1="18" x2="3.01" y2="18"/>
          </svg>
        </div>
      </div>
    </div>

    <!-- 搜索栏 -->
    <div class="search-section" v-if="showSearch">
      <div class="search-bar">
        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#999" stroke-width="2">
          <circle cx="11" cy="11" r="8"/>
          <path d="m21 21-4.35-4.35"/>
        </svg>
        <input 
          type="text" 
          placeholder="搜索医疗记录..." 
          v-model="searchQuery"
          @input="handleSearch"
        />
      </div>
    </div>

    <!-- 筛选选项 -->
    <div class="filter-section" v-if="showFilter">
      <div class="filter-tabs">
        <div 
          class="filter-tab" 
          :class="{ active: activeFilter === 'all' }"
          @click="setFilter('all')"
        >
          全部结果
        </div>
        <div 
          class="filter-tab" 
          :class="{ active: activeFilter === 'favorites' }"
          @click="setFilter('favorites')"
        >
          收藏
        </div>
      </div>
    </div>

    <!-- 医疗记录列表 -->
    <div class="records-list" ref="listContainer" @scroll="handleScroll">
      <div 
        class="record-item" 
        v-for="record in displayedRecords" 
        :key="record.id"
        @click="viewRecord(record)"
      >
        <div class="record-icon">
          <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#1877F2" stroke-width="2">
            <path d="M9 12l2 2 4-4"/>
            <path d="M21 12c-1 0-2-1-2-2s1-2 2-2 2 1 2 2-1 2-2 2z"/>
            <path d="M3 12c1 0 2-1 2-2s-1-2-2-2-2 1-2 2 1 2 2 2z"/>
          </svg>
        </div>
        
        <div class="record-details">
          <h3 class="record-title">{{ record.title }}</h3>
          <p class="record-time">{{ record.time }}</p>
          <div class="hospital-tag">{{ record.hospital }}</div>
        </div>
        
        <div class="record-actions">
          <div 
            class="favorite-btn" 
            :class="{ active: record.isFavorite }"
            @click.stop="toggleFavorite(record)"
          >
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
              <path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"/>
            </svg>
          </div>
        </div>
      </div>

      <!-- 加载更多指示器 -->
      <div class="load-more" v-if="isLoading">
        <div class="loading-spinner">
          <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#1877F2" stroke-width="2">
            <circle cx="12" cy="12" r="10" stroke-dasharray="31.416" stroke-dashoffset="31.416">
              <animate attributeName="stroke-dasharray" dur="2s" values="0 31.416;15.708 15.708;0 31.416" repeatCount="indefinite"/>
              <animate attributeName="stroke-dashoffset" dur="2s" values="0;-15.708;-31.416" repeatCount="indefinite"/>
            </circle>
          </svg>
        </div>
        <span class="loading-text">加载中...</span>
      </div>

      <!-- 没有更多数据提示 -->
      <div class="no-more" v-if="!hasMore && displayedRecords.length > 0">
        <span class="no-more-text">没有更多数据了</span>
      </div>
    </div>

    <!-- 空状态 -->
    <div class="empty-state" v-if="displayedRecords.length === 0 && !isLoading">
      <div class="empty-icon">
        <svg width="64" height="64" viewBox="0 0 24 24" fill="none" stroke="#ccc" stroke-width="1">
          <path d="M9 12l2 2 4-4"/>
          <path d="M21 12c-1 0-2-1-2-2s1-2 2-2 2 1 2 2-1 2-2 2z"/>
          <path d="M3 12c1 0 2-1 2-2s-1-2-2-2-2 1-2 2 1 2 2 2z"/>
        </svg>
      </div>
      <h3 class="empty-title">暂无医疗记录</h3>
      <p class="empty-desc">您还没有医疗记录</p>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, nextTick } from 'vue'
import { useRouter } from 'vue-router'

const router = useRouter()

// 响应式数据
const searchQuery = ref('')
const showSearch = ref(false)
const showFilter = ref(false)
const activeFilter = ref('all')
const isLoading = ref(false)
const hasMore = ref(true)
const currentPage = ref(1)
const pageSize = ref(10)
const listContainer = ref<HTMLElement>()

// 生成模拟医疗记录数据
const generateMockRecords = (startId: number, count: number) => {
  const records = []
  const titles = [
    'X射线结果', '一般检查', '一般血液分析', '心电图', 'B超检查',
    'CT扫描', '核磁共振', '病理检查', '生化检查', '免疫检查',
    '微生物检查', '遗传检查', '内分泌检查', '肿瘤标志物', '过敏原检查',
    '骨密度检查', '肺功能检查', '脑电图', '肌电图', '眼底检查'
  ]
  const hospitals = [
    '医科大学附属医院', '北京仁和医院', '协和医院', '人民医院', '中医院',
    '妇幼保健院', '肿瘤医院', '口腔医院', '眼科医院', '骨科医院'
  ]
  const timeOptions = [
    '30分钟', '1小时', '2小时', '3小时', '1天', '2天', '1周'
  ]

  for (let i = 0; i < count; i++) {
    const id = startId + i
    const title = titles[Math.floor(Math.random() * titles.length)]
    const hospital = hospitals[Math.floor(Math.random() * hospitals.length)]
    const isFavorite = Math.random() > 0.8 // 20%概率为收藏
    
    // 生成时间（最近记录显示时间，较远记录显示日期）
    let time
    if (Math.random() > 0.6) {
      // 显示时间
      time = timeOptions[Math.floor(Math.random() * timeOptions.length)]
    } else {
      // 显示日期
      const date = new Date()
      date.setDate(date.getDate() - Math.floor(Math.random() * 365))
      time = date.toISOString().split('T')[0]
    }

    records.push({
      id,
      title,
      time,
      hospital,
      isFavorite
    })
  }

  return records
}

// 所有医疗记录数据
const allRecords = ref(generateMockRecords(1, 50))

// 当前显示的记录数据（用于懒加载）
const displayedRecords = ref<any[]>([])

// 计算属性
const filteredRecords = computed(() => {
  let filtered = allRecords.value

  // 按收藏筛选
  if (activeFilter.value === 'favorites') {
    filtered = filtered.filter(r => r.isFavorite)
  }

  // 按搜索关键词筛选
  if (searchQuery.value.trim()) {
    const query = searchQuery.value.toLowerCase()
    filtered = filtered.filter(r => 
      r.title.toLowerCase().includes(query) ||
      r.hospital.toLowerCase().includes(query)
    )
  }

  return filtered
})

// 加载更多数据
const loadMoreData = async () => {
  if (isLoading.value || !hasMore.value) return

  isLoading.value = true
  
  // 模拟网络延迟
  await new Promise(resolve => setTimeout(resolve, 800))

  const filtered = filteredRecords.value
  const startIndex = (currentPage.value - 1) * pageSize.value
  const endIndex = startIndex + pageSize.value
  const newData = filtered.slice(startIndex, endIndex)

  if (newData.length > 0) {
    displayedRecords.value.push(...newData)
    currentPage.value++
  }

  // 检查是否还有更多数据
  hasMore.value = endIndex < filtered.length
  isLoading.value = false
}

// 重置数据
const resetData = () => {
  displayedRecords.value = []
  currentPage.value = 1
  hasMore.value = true
  loadMoreData()
}

// 滚动处理
const handleScroll = (event: Event) => {
  const target = event.target as HTMLElement
  const { scrollTop, scrollHeight, clientHeight } = target
  
  // 当滚动到距离底部100px时加载更多
  if (scrollHeight - scrollTop - clientHeight < 100 && !isLoading.value && hasMore.value) {
    loadMoreData()
  }
}

// 方法
const goBack = () => {
  router.back()
}

const toggleSearch = () => {
  showSearch.value = !showSearch.value
  if (!showSearch.value) {
    searchQuery.value = ''
    resetData()
  }
}

const toggleFilter = () => {
  showFilter.value = !showFilter.value
}

const handleSearch = () => {
  resetData()
}

const setFilter = (filter: string) => {
  activeFilter.value = filter
  resetData()
}

const viewRecord = (record: any) => {
  console.log('查看医疗记录:', record)
  // 这里可以跳转到记录详情页
}

const toggleFavorite = (record: any) => {
  record.isFavorite = !record.isFavorite
  console.log('切换收藏状态:', record.title, record.isFavorite)
  // 这里可以调用API更新收藏状态
}

// 组件挂载时加载初始数据
onMounted(() => {
  nextTick(() => {
    loadMoreData()
  })
})
</script>

<style scoped lang="scss">
.medical-records {
  min-height: 100vh;
  background: #f5f5f5;
  position: relative;
}

.status-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 20px;
  background: #000;
  color: white;
  font-size: 14px;
  font-weight: 600;

  .status-right {
    display: flex;
    gap: 5px;
    align-items: center;
  }

  .signal, .wifi, .battery {
    width: 20px;
    height: 12px;
    background: #fff;
    border-radius: 2px;
  }

  .signal {
    background: linear-gradient(90deg, #fff 0%, #fff 80%, transparent 80%);
  }

  .wifi {
    background: radial-gradient(circle at 50% 50%, transparent 0, transparent 3px, #fff 3px, #fff 6px, transparent 6px);
  }

  .battery {
    position: relative;
    
    &::after {
      content: '';
      position: absolute;
      right: -3px;
      top: 50%;
      transform: translateY(-50%);
      width: 2px;
      height: 6px;
      background: #fff;
      border-radius: 0 1px 1px 0;
    }
  }
}

.header {
  background: linear-gradient(135deg, #1877F2 0%, #005AFF 100%);
  padding: 20px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  color: white;
  position: relative;

  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><defs><pattern id="dots" x="0" y="0" width="20" height="20" patternUnits="userSpaceOnUse"><circle cx="10" cy="10" r="1" fill="rgba(255,255,255,0.1)"/></pattern></defs><rect width="100" height="100" fill="url(%23dots)"/></svg>');
    opacity: 0.3;
  }
}

.nav-back, .nav-action {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.2);
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: background 0.3s ease;
  position: relative;
  z-index: 1;

  &:hover {
    background: rgba(255, 255, 255, 0.3);
  }
}

.nav-actions {
  display: flex;
  gap: 8px;
}

.page-title {
  font-size: 20px;
  font-weight: 700;
  margin: 0;
  position: relative;
  z-index: 1;
}

.search-section {
  background: white;
  padding: 15px 20px;
  border-bottom: 1px solid #e0e0e0;
}

.search-bar {
  display: flex;
  align-items: center;
  background: #f8f9fa;
  border-radius: 12px;
  padding: 12px 16px;
  gap: 12px;

  input {
    flex: 1;
    border: none;
    background: transparent;
    font-size: 16px;
    outline: none;
    color: #333;

    &::placeholder {
      color: #999;
    }
  }
}

.filter-section {
  background: white;
  padding: 15px 20px;
  border-bottom: 1px solid #e0e0e0;
}

.filter-tabs {
  display: flex;
  gap: 12px;
}

.filter-tab {
  padding: 8px 16px;
  border-radius: 20px;
  background: #f8f9fa;
  color: #666;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;

  &.active {
    background: #1877F2;
    color: white;

    &::after {
      content: '';
      position: absolute;
      bottom: -15px;
      left: 50%;
      transform: translateX(-50%);
      width: 20px;
      height: 3px;
      background: #1877F2;
      border-radius: 2px;
    }
  }

  &:hover {
    background: #e9ecef;
    
    &.active {
      background: #1877F2;
    }
  }
}

.records-list {
  padding: 20px;
  max-height: calc(100vh - 200px);
  overflow-y: auto;
  scroll-behavior: smooth;
}

.record-item {
  background: white;
  border-radius: 12px;
  padding: 16px;
  margin-bottom: 12px;
  display: flex;
  align-items: center;
  gap: 16px;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
  }
}

.record-icon {
  width: 48px;
  height: 48px;
  border-radius: 8px;
  background: #f0f8ff;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.record-details {
  flex: 1;
  min-width: 0;
}

.record-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin: 0 0 4px 0;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.record-time {
  font-size: 14px;
  color: #666;
  margin: 0 0 8px 0;
}

.hospital-tag {
  display: inline-block;
  padding: 4px 8px;
  background: #f8f9fa;
  color: #666;
  font-size: 12px;
  border-radius: 12px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 120px;
}

.record-actions {
  flex-shrink: 0;
}

.favorite-btn {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: #f8f9fa;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s ease;
  color: #999;

  &.active {
    background: #ffe6e6;
    color: #ff4757;

    svg {
      fill: #ff4757;
    }
  }

  &:hover {
    background: #ffe6e6;
    color: #ff4757;
    transform: scale(1.1);
  }

  svg {
    transition: all 0.3s ease;
  }
}

// 加载更多样式
.load-more {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 20px;
  color: #666;
}

.loading-spinner {
  margin-bottom: 8px;
}

.loading-text {
  font-size: 14px;
  color: #999;
}

.no-more {
  display: flex;
  justify-content: center;
  padding: 20px;
}

.no-more-text {
  font-size: 14px;
  color: #999;
  font-style: italic;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  text-align: center;
}

.empty-icon {
  margin-bottom: 20px;
}

.empty-title {
  font-size: 18px;
  font-weight: 600;
  color: #666;
  margin: 0 0 8px 0;
}

.empty-desc {
  font-size: 14px;
  color: #999;
  margin: 0;
}

@media (max-width: 768px) {
  .records-list {
    padding: 15px;
  }

  .record-item {
    padding: 12px;
  }

  .record-icon {
    width: 40px;
    height: 40px;
  }

  .record-title {
    font-size: 14px;
  }

  .record-time {
    font-size: 12px;
  }

  .hospital-tag {
    font-size: 11px;
    max-width: 100px;
  }
}

@media (max-width: 480px) {
  .header {
    padding: 15px;
  }

  .page-title {
    font-size: 18px;
  }

  .search-section {
    padding: 12px 15px;
  }

  .filter-section {
    padding: 12px 15px;
  }

  .filter-tabs {
    gap: 8px;
  }

  .filter-tab {
    padding: 6px 12px;
    font-size: 12px;
  }
}
</style> 